package wnhz.com.business.shareshop.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerClickListener;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.base.MyBaseActivity;
import wnhz.com.business.base.MyBaseFragment;
import wnhz.com.business.groupshop.bean.HomeIndexBean;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.netcallback.DialogCallback;
import wnhz.com.business.netcallback.DialogCallback;
import wnhz.com.business.rebateshop.activity.home.RebateGoodsDetailsActivity;
import wnhz.com.business.rebateshop.activity.home.ShareFriandActivity;
import wnhz.com.business.shareshop.HomeBean;
import wnhz.com.business.shareshop.activity.classify.ClassifGoodsActivity;
import wnhz.com.business.shareshop.activity.home.ClassFromHomeActivity;
import wnhz.com.business.shareshop.activity.home.EverydayPhoneActivity;
import wnhz.com.business.shareshop.activity.home.RebateGoodsDetailsActivityS;
import wnhz.com.business.shareshop.activity.home.WebViewHomeActivity;
import wnhz.com.business.shareshop.bean.ShareHomDataBean;
import wnhz.com.business.uitls.GlideImageLoader;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.Prefer;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.decoration.DividerGridItemDecoration;
import wnhz.com.business.view.TranslucentActionBar;

/**
 * 共享商城首页
 */

public class HomeFragment extends MyBaseFragment implements ActionBarClickListener, OnRefreshLoadmoreListener {
    private MyBaseActivity activity;

    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;//顶部

    @BindView(R.id.banner_rebatehome_banner)
    Banner banner_rebatehome_banner;//首页banner图

    @BindView(R.id.ry_rebatehome_bootlist)
    RecyclerView ry_rebatehome_bootlist;//底部

    @BindView(R.id.relative_left)
    RelativeLayout relativeLeft; //天天搞基

    @BindView(R.id.relative_right_up)
    RelativeLayout relativeRightRp;  //办公神器

    @BindView(R.id.relative_low_left)
    RelativeLayout relativeLowLeft; //好用家电

    @BindView(R.id.relative_electronic_Superman)
    RelativeLayout relativeElectronicSuperman; //电子超人

    //   首页中间部分
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.text_view_content)
    TextView text_view_content;
    @BindView(R.id.iv_left)
    ImageView iv_left;

    @BindView(R.id.textView1)
    TextView textView1;
    @BindView(R.id.text_view_content_right)
    TextView text_view_content_right;
    @BindView(R.id.iv_img1)
    ImageView iv_img1;

    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.text_view_content_low_left)
    TextView text_view_content_low_left;
    @BindView(R.id.iv_img2)
    ImageView iv_img2;

    @BindView(R.id.textView3)
    TextView textView3;
    @BindView(R.id.text_view_content_low_right)
    TextView text_view_content_low_right;
    @BindView(R.id.iv_img3)
    ImageView iv_img3;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private List<ShareHomDataBean.InfoBean.BannerBean> bannerBeanList = new ArrayList<ShareHomDataBean.InfoBean.BannerBean>();

    private List<String> urllist = new ArrayList<>();
    private List<String> bannerlist = new ArrayList<>();
    private String cate_id0,cate_id1,cate_id2,cate_id3;
    private BaseRVAdapter adapter;
   private List<ShareHomDataBean.InfoBean.CateListBean> hotData = new ArrayList<ShareHomDataBean.InfoBean.CateListBean>();
    @Override
    protected void handleMsg(Message msg) {

    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_share_home, container, false);
        ButterKnife.bind(this, view);
        activity = (MyBaseActivity) getActivity();
        actionbar.setVisibility(View.VISIBLE);
        actionbar.setData("共享商城", /*R.drawable.ic_lefft_white*/0, null, 0, null, 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }

        initSmartRefreshLayout();
        getHomFragmentData();

        return view;
    }

    private void initSmartRefreshLayout() {
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        loadData();
    }


    /**
     * 获取首页数据
     */
    private void loadData() {
        urllist.clear();
        bannerlist.clear();
        Map<String,String> map = new HashMap<>();
        if (TextUtils.isEmpty(MyApplication.getToken())){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }else {
            map.put("token", MyApplication.getToken());
            map.put("cateId", "");
            map.put("page", "0");
            map.put("goods_type", "4");//1.拼团  2.返利  3.免费
            OkGo.<String>post(Url.HOME_INDEXDADA)
                    .tag(this)
                    .params(map, false)
                    .execute(new DialogCallback<String>(activity) {

                        @Override
                        public void onSuccess(Response<String> response) {
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response.body().toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String res = jsonObject.optString("re");
                            if (res.equals("1")){
                                Gson gson = new Gson();
                                HomeBean homeBean = gson.fromJson(response.body().toString(), HomeBean.class);
                            }else{
                                ToastUtils.showToast(activity,"暂无数据");
                            }
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.finishLoadmore();
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                            mRefreshLayout.setEnableLoadmore(false);
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                        }
                    });
        }
    }

    /**
     * banner图
     */
    private void initBanner() {
        banner_rebatehome_banner.setImageLoader(new GlideImageLoader());
        banner_rebatehome_banner.setImages(bannerlist);
        banner_rebatehome_banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if(!TextUtils.isEmpty(bannerBeanList.get(position).getUrl())&&(bannerBeanList.get(position).getGoodsId().equals("0"))){
                   Intent intent = new Intent(activity, WebViewHomeActivity.class);
                    intent.putExtra("title",bannerBeanList.get(position).getTitle());
                    intent.putExtra("url",bannerBeanList.get(position).getUrl());
                    activity.startActivity(intent);
                }else if(TextUtils.isEmpty(bannerBeanList.get(position).getUrl())&&(!bannerBeanList.get(position).getGoodsId().equals("0"))){
                    startActivity(RebateGoodsDetailsActivityS.createIntent(activity, bannerBeanList.get(position).getGoodsId(), bannerBeanList.get(position).getPic(), "4"));
                }
            }
        });
        banner_rebatehome_banner.start();
        bannerlist.clear();
    }


    //轮播图片列表地址
    private void initTestBannerlist(List<ShareHomDataBean.InfoBean.BannerBean> bannerBeanList) {
        for (int i = 0; i < bannerBeanList.size(); i++) {
            bannerlist.add(bannerBeanList.get(i).getPic());
        }
        initBanner();
    }


    //猜你喜欢图片列表地址
    private void initTestGallylist(List<ShareHomDataBean.InfoBean.GoodsBean> goods) {
        ry_rebatehome_bootlist.setLayoutManager(new GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false));
        ry_rebatehome_bootlist.addItemDecoration(new DividerGridItemDecoration(15));
        urllist.clear();
        for (int i = 0; i < goods.size(); i++) {
            urllist.add(goods.get(i).getLogo_pic());
        }
        initList(goods);
    }


    /*
     *底部商品列表
     */
    private void initList(final List<ShareHomDataBean.InfoBean.GoodsBean> goods) {

        adapter = new BaseRVAdapter(activity, goods) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_rebatehome_bootlist;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                holder.setTextView(R.id.item_tv_rebatehome_name, goods.get(position).getGoods_name());
                holder.setTextView(R.id.item_tv_rebatehome_info,goods.get(position).getGoods_title() + " " + goods.get(position).getGoods_des());
                holder.setTextView(R.id.item_tv_rebatehome_price, "押金￥" + goods.get(position).getPrice());
                Glide.with(activity).load(goods.get(position).getLogo_pic()).into(holder.getImageView(R.id.item_img_rebatehome));
                holder.getView(R.id.item_tv_rebatehome_share).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //跳转分享页面  (页面标题: 分享商品给好友)
                        startActivity(ShareFriandActivity.createIntent(getContext(),goods.get(position).getLogo_pic(),"",goods.get(position).getGoods_name(),goods.get(position).getGroup_price()));
                    }
                });
            }
        };

        adapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                startActivity(RebateGoodsDetailsActivityS.createIntent(activity, goods.get(position).getGoods_id(), goods.get(position).getLogo_pic(), "4"));
            }
        });
        ry_rebatehome_bootlist.setAdapter(adapter);
    }

    @OnClick({R.id.relative_left, R.id.relative_right_up, R.id.relative_low_left, R.id.relative_electronic_Superman})
    public void ininOnClick(View v) {
        Intent intent = new Intent(getActivity(),ClassFromHomeActivity.class);
        switch (v.getId()) {
            case R.id.relative_left:
                intent.putExtra("cate_id",cate_id0);
                intent.putExtra("title",hotData.get(0).getClassname());
                activity.startActivity(intent);
                break;
            case R.id.relative_right_up:
                intent.putExtra("cate_id",cate_id1);
                intent.putExtra("title",hotData.get(1).getClassname());
                activity.startActivity(intent);
                break;
            case R.id.relative_low_left:
                intent.putExtra("cate_id",cate_id2);
                intent.putExtra("title",hotData.get(2).getClassname());
                activity.startActivity(intent);
                break;
            case R.id.relative_electronic_Superman:
                intent.putExtra("cate_id",cate_id3);
                intent.putExtra("title",hotData.get(3).getClassname());
                activity.startActivity(intent);
                break;

        }
    }

    @Override
    public void onLeftClick() {

    }

    @Override
    public void onRightClick() {

    }


    @Override
    public void onEditTextClick() {

    }


    public void getHomFragmentData() {
        Map<String, String> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
//        map.put("cateId", "1");
        map.put("page", "0");
        map.put("goods_type", "4");
        LogUtils.e("wxf", "共享商城首页数据" + Url.HOME_INDEXDADA);
        OkGo.<ShareHomDataBean>post(Url.HOME_INDEXDADA).tag(this).params(map, false).execute(new DialogCallback<ShareHomDataBean>(getActivity()) {
            @Override
            public void onSuccess(Response<ShareHomDataBean> response) {

                if (response.body().getRe().equals("1")) {
                    LogUtils.e("wxf", "共享商城" + response.body().toString());
                    bannerBeanList = response.body().getInfo().getBanner();//最上面的数据
                    initTestBannerlist(bannerBeanList);
                    hotData = response.body().getInfo().getCate_list();//中间的数据
                    sethotData();
                    initTestGallylist(response.body().getInfo().getGoods());//最下面的数据
                } else {
                    ToastUtils.showToast(getActivity(), response.body().getRe());
                }


            }
        });

    }

    public void sethotData() {
        try {
            textView.setText(hotData.get(0).getClassname());
            text_view_content.setText(hotData.get(0).getTitle());
            Glide.with(activity).load(hotData.get(0).getPic()).into(iv_left);
            cate_id0 = hotData.get(0).getCate_id();

            textView1.setText(hotData.get(1).getClassname());
            text_view_content_right.setText(hotData.get(1).getTitle());
            Glide.with(activity).load(hotData.get(1).getPic()).into(iv_img1);
            cate_id1 = hotData.get(1).getCate_id();

            textView2.setText(hotData.get(2).getClassname());
            text_view_content_low_left.setText(hotData.get(2).getTitle());
            Glide.with(activity).load(hotData.get(2).getPic()).into(iv_img2);
            cate_id2 = hotData.get(2).getCate_id();

            textView3.setText(hotData.get(3).getClassname());
            text_view_content_low_right.setText(hotData.get(3).getTitle());
            Glide.with(activity).load(hotData.get(3).getPic()).into(iv_img3);
            cate_id3 = hotData.get(3).getCate_id();
        } catch (Exception e) {
            LogUtils.e("wxf", "找后台添加数据" + e.toString());
        }
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {

    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mRefreshLayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                loadData();
            }
        },2000);
    }
}
